<!--终端新增modal-->
<template xmlns='http://www.w3.org/1999/html'>
  <j-modal
    :title="'终端' + title "
    width='80%'
    :visible='visible'
    :confirmLoading='confirmLoading'
    switchFullscreen
    @cancel='handleCancel'
    @ok='handleOk'
    cancelText='关闭'
    style='height: 100%;overflow: auto;padding-bottom: 53px;'>
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button @click='handleOk' type='primary' :loading='confirmLoading' v-if='!disableSubmit'>确认</a-button>
    </template>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row :gutter='24'>
          <div class='basicNew'>基本信息</div>
          <a-col :md='8' :sm='24'>
            <a-form-item label='终端名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input :disabled='disableSubmit' placeholder='请输入终端名称'
                       v-decorator="['terminalName', validatorRules.terminalName]" />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='终端类型'
              >
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange='true'
                                 dictCode='terminal_type'
                                 @change='e =>terminalTypeC(e)'
                                 :disabled='disableSubmit'
                                 v-decorator="['terminalType',validatorRules.terminalType]" placeholder='请选择终端类型' />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='终端细类'
              >
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange='true'
                                 :dictCode='changingType'
                                 :disabled='disableSubmit || changingType == "" || !changingType'
                                 v-decorator="['fine',validatorRules.terminalType]" placeholder='请选择终端细类' />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='省/市/区'
              :required='true'
            >
              <j-area-linkage
                :disabled='disableSubmit'
                @change='areaChange'
                v-model='areaLinkage'
                type='cascader'
                :province.sync='province'
                :city.sync='city'
                :area.sync='area'
              />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item label='详细地址' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input :disabled='disableSubmit' placeholder='请输入详细地址'
                       v-decorator="['address', validatorRules.terminalName]" />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='所属组织'
              >
              <a-tree-select
                :disabled='disableSubmit'
                style='width:100%'
                :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                :treeData='treeData'
                v-decorator="['orgCode', validatorRules.terminalType]"
                placeholder='请选择组织'
                show-search
                tree-default-expand-all
                tree-node-filter-prop='title'
                :replaceFields="{children:'children', title:'orgName', key:'orgCode', value: 'orgCode' }">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='商超组织'>
              <a-input-search :disabled='disableSubmit' placeholder='请选择商超组织'
                              v-decorator="[ 'custOrgName', changingType=='tpm_shang_fine'?validatorRules.terminalType:{}]"
                              readOnly enter-button @search='custOrgCodeSearch("custOrgCode")' />
              <a-input type='hidden' v-decorator="[ 'custOrgCode']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='终端规格'
              >
              <cn-dict-select-tag :disabled='disableSubmit' :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange='true'
                                 dictCode='tpm_specifications'
                                 v-decorator="['specifications',validatorRules.terminalType]" placeholder='请选择终端规格' />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='归属类型'
              >
              <cn-dict-select-tag :disabled='disableSubmit' :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange='true'
                                 dictCode='tpm_attribution_type'
                                 v-decorator="['attributionType',validatorRules.terminalType]"
                                 placeholder='请选择归属类型' />
            </a-form-item>

          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='店招图片'
            >
              <div class='dianzhao-pic'>
              <j-image-upload :disabled='disableSubmit' class='avatar-uploader' text='上传' :isMultiple='false' v-decorator="[ 'avatar']">
              </j-image-upload>
              <viewer :images="images">
                <a v-if='this.form.getFieldValue("avatar")' @click="tableEdit()" style="position: relative;textAlign:center">
                  查看图片
                  <img v-for="(img, indexx) in images" :src="img" :key="indexx" class="tableImages">
                </a>
              </viewer>
              </div>
            </a-form-item>
          </a-col>
          <a-col :md='24' :sm='24'>
            <div class='basicNew1'>联系人信息</div>
          </a-col>
          <div style='float: left;width: 100%;display: flex;' v-for='(item,index) in formItems' :key='index'>
            <div style='flex: 1'>
              <a-col :md='8' :sm='24'>
                <a-form-item label='联系人' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input :disabled='disableSubmit' placeholder='请输入联系人姓名'
                           v-model='item.name' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='联系方式' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input :disabled='disableSubmit' placeholder='请输入联系方式' v-model='item.telephone' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='主联系人' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-select
                    :disabled='disableSubmit'
                    placeholder='请选择'
                    v-model='item.isMain'>
                    <a-select-option value='0'> 否</a-select-option>
                    <a-select-option value='1'> 是</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </div>
            <a-button shape='circle' icon='plus' class='addIcon' :disabled='disableSubmit' v-if='index==0'
                      @click='addTicket'></a-button>
            <a-button shape='circle' icon='minus' class='addIcon' :disabled='disableSubmit' v-else
                      @click='delTicket(index)'></a-button>
          </div>
          <a-col :md='24' :sm='24'>
            <div class='basicNew1'>供应关系</div>
          </a-col>
          <div style='float: left;width: 100%;display: flex;'>
            <div style='flex: 1'>
              <a-col :md='8' :sm='24'>
                <a-form-item label='供货经销商' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input-search :disabled='disableSubmit' placeholder='请选择供货经销商'
                                  v-decorator="[ 'customerName', validatorRules.terminalType]"
                                  readOnly enter-button @search='custSearch("indexs","customerCode")' />
                  <a-input type='hidden' v-decorator="[ 'customerCode']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='负责岗位' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input-search :disabled='disableSubmit' placeholder='请选择负责岗位'
                                  v-decorator="[ 'personPosName', validatorRules.terminalType]"
                                  readOnly enter-button @search='personSearch("personPosCode")' />
                  <a-input type='hidden' v-decorator="[ 'personPosCode']"></a-input>
                  <a-input type='hidden' v-decorator="[ 'personName']"></a-input>
                </a-form-item>

              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='负责人' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input :disabled='disableSubmit' placeholder='请选择'
                                  v-decorator="[ 'personName', validatorRules.terminalType]"
                                  readOnly/>
                </a-form-item>

              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='所在组织' :labelCol='labelCol' :wrapperCol='wrapperCol' :required='true'>
                  <a-input :disabled='disableSubmit' readOnly placeholder='请输入所在组织'
                           v-decorator="[ 'organizationName']"></a-input>
                  <a-input :disabled='disableSubmit' type='hidden'
                           v-decorator="[ 'organization', validatorRules.terminalType]" />
                </a-form-item>
              </a-col>
            </div>
            <!--            <div class='addIcon' @click='addTicket2'>+</div>-->
          </div>
        </a-row>
      </a-form>

      <proChose ref='prochoose' v-bind='modalProps' @okbro='okbropro'></proChose>
      <formItemsDraw ref='modalForm' @okpopup='modalFormOk' v-bind='configw'></formItemsDraw>
    </a-spin>
  </j-modal>
</template>

<script>

import pick from 'lodash.pick'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import JImageUpload from '@/components/cn-form/JImageUpload'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JSelectUserByDep from '@/components/cn-select-popup/JSelectUserByDep'
import JSelectTerminal from '@/components/cn-select-popup/JSelectTerminal'
import Area from '@comp/utils/Area'
import proChose from '@comp/cn-components/ProChose'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import formItemsDraw from '@comp/cn-components/formItemsDraw'
import { queryDepartTreeList } from '@/api/api'
import { getAction, postAction, deleteAction } from '@/api/manage'

export default {
  name: 'terminalManageModal',
  components: {
    JImageUpload,
    AFormItem,
    ATextarea,
    JTreeSelect,
    JSelectUserByDep,
    JSelectTerminal,
    JAreaLinkage,
    proChose,
    formItemsDraw
  },
  data() {
    return {
      images:[],
      disableSubmit:false,
      changingType: '',
      custList: [],
      name: '',
      formItems: [{
        name: '',
        telephone: '',
        isMain: ''
      }],
      itemModal:
        {
          name: '',
          telephone: '',
          isMain: ''
        },
      areaLinkage: '',
      province: '',
      city: '',
      area: '',
      custCode: '',
      custName: '',
      showCode: 4,
      terminalName: '',
      terminalCode: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: {
          span: 24
        }
        ,
        sm: {
          span: 6
        }
      }
      ,
      wrapperCol: {
        xs: {
          span: 24
        }
        ,
        sm: {
          span: 18
        }
      }
      ,
      labelCol1: {
        xs: {
          span: 24
        }
        ,
        sm: {
          span: 3
        }
      }
      ,
      wrapperCol1: {
        xs: {
          span: 24
        }
        ,
        sm: {
          span: 21
        }
      }
      ,
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        terminalName: {
          rules: [{ required: true, message: '请输入!', trigger: 'submit' }]
        },
        terminalType: {
          rules: [{ required: true, message: '请选择!', trigger: 'submit' }]
        }
      },
      url: {
        add: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateTerminal'
      },
      treeData: []
    }
  },
  methods: {
    tableEdit(){
      this.images = [this.form.getFieldValue("avatar")]
    },
    handlePreview(e){
      console.log(e)
    },
    terminalTypeC(e) {
      this.changingType = e
    },
    personChange(e) {
      console.log(e)
    },
    loadTree() {
      var that = this
      queryDepartTreeList().then((res) => {
        if (res.success) {
          that.treeData = []
          let treeList = res.result
          for (let a = 0; a < treeList.length; a++) {
            let temp = treeList[a]
            temp.isLeaf = temp.leaf
            that.treeData.push(temp)
          }
        }
      })
    },

    addTicket() {
      // let modal = JSON.parse(JSON.stringify(this.itemModal))
      let modal = { name: '', telephone: '', isMain: '' }
      this.formItems.push(modal)
      console.log(this.formItems)
    },
    delTicket(index) {
      this.formItems.splice(index, 1)
    },


    modalFormOk(e1, e2) {
      console.log(e1, e2)
    },
    // addTicket() {
    //   this.$refs.modalForm.edit()
    // },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()

      }
    },
    areaChange(code) {
      let cities = this.areaData.getText(code, '多个值').cities
      let codes = this.areaData.getText(code, '多个值').codes
      this.model.province = cities.split('/')[0]
      this.model.city = cities.split('/')[1]
      this.model.area = cities.split('/')[2]
      this.model.provinceCode = this.dealCode(codes.split('/')[0], 2).join('')
      this.model.cityCode = this.dealCode(codes.split('/')[1], 4).join('')
      this.model.areaCode = this.dealCode(codes.split('/')[2], 6).join('')
      console.log(this.model)
    },
    // params:code:编码，count位数
    dealCode(code, count) {
      console.log(code)
      let num = code.split('')
      let codes = []
      for (let i = 0; i < count; i++) {
        codes.push(num[i])
      }
      return codes
    },
    add() {
      this.edit({})
    },
    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.changingType = this.model.terminalType || ' '
      let pca = this.model.province + '/' + this.model.city + '/' + this.model.area
      this.areaLinkage = this.areaData.getAreaCodeByText(pca) || ''
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
        this.changingType = this.model.terminalType
        this.formItems = this.model.extendVos || [this.itemModal]
      })
    },
    close() {
      this.visible = false
      this.formItems = [{
        name: '',
        telephone: '',
        isMain: ''
      }]
    },
    okbropro(record, status, status2, status3) {
      console.log(record, status, status2, status3)
      if (status2 == 'customerCode') {
        this.form.setFieldsValue({
          customerCode: record[0].erpCode,
          customerName: record[0].customerName
        })
      } else if (status == 'personPosCode') {
        this.form.setFieldsValue({
          personPosCode: record[0].positionCode,
          personPosName: record[0].positionName + '/' + record[0].realname,
          personName:record[0].realname,
          organization: record[0].orgCode,
          organizationName: record[0].orgName
        })
      } else if (status == 'custOrgCode') {
        this.form.setFieldsValue({
          custOrgName: record[0].superName,
          custOrgCode: record[0].superCode
        })
      }
    },
    custOrgCodeSearch(status) {
      this.$refs.prochoose.rowKey = 'superCode'
      let formconfig = [
        {
          key: 'superCode',
          label: '商超编码'
        },
        {
          key: 'superName',
          label: '商超名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '商超编码',
            align: 'left',
            dataIndex: 'superCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '商超名称',
            align: 'left',
            dataIndex: 'superName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnSysSuper/getSuperTypeTree',
        multiple: false,
        columW: 10
      }
      this.name = '商超'
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'superName')
    },
    personSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      this.$refs.prochoose.isorter.permflag = 'ter_position_jurisdiction_impl'
      let formconfig = [
        {
          key: 'realname',
          label: '用户名称'
        },
        {
          key: 'positionName',
          label: '岗位名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '岗位编码',
            align: 'left',
            dataIndex: 'positionCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '岗位名称',
            align: 'left',
            dataIndex: 'positionName',
            width: 120,
            ellipsis: true
          },
          {
            title: '用户名称',
            align: 'left',
            dataIndex: 'realname',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnPositionController/findPageListByJurisdiction',
        multiple: false,
        columW: 12
      }
      this.name = '岗位'
      let dataSource = []
      if (this.form.getFieldValue('positionCode')) {
        dataSource = [{
          positionCode: this.form.getFieldValue('positionCode'),
          positionName: this.form.getFieldValue('positionName')
        }]
      }
      console.log(dataSource)
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'personPosCode', dataSource)
    },
    custSearch(status = 'customerCode', status2) {
      if (status2 == 'customerCode') {
        this.$refs.prochoose.rowKey = 'id'
        this.$refs.prochoose.isorter.permflag = 'ter_cust_jurisdiction_impl'
        let formconfig = [
          // {
          //   key: 'customerCode',
          //   label: '经销商编码'
          // },
          {
            key: 'customerName',
            label: '经销商名称'
          }
        ]
        let tableconfig = {
          columns: [
            {
              title: '经销商编码',
              align: 'center',
              dataIndex: 'erpCode',
              width: 120,
              ellipsis: true
            },
            {
              title: '经销商名称',
              align: 'center',
              dataIndex: 'customerName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/customerController/findPageListByJurisdiction',
          multiple: false,
          columW: 11
        }
        // let dataSource = []
        // if (this.form.getFieldValue('custCode')) {
        //   dataSource = [{
        //     custCode: this.form.getFieldValue('custCode'),
        //     custName: this.form.getFieldValue('custName')
        //   }]
        // }
        this.name = '经销商'
        this.$refs.prochoose.edit(formconfig, tableconfig, status, status2, null)
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
    if(!this.areaLinkage.trim()){
      this.$message.info('请选择省市区')
      return
    }
    let a = 'good'
      this.formItems.some(item =>{
        if(!item.name || !item.telephone || !item.isMain){
          this.$message.info('请完善联系人信息')
          a = 'bad'
          return true
        }
      })
      if(a == 'bad'){
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          // if (values.imgs && values.imgs.length) {
          //   values.imgs.slice(0).map((url, index) => {
          //     extendVos.push({
          //       dataType: 1,
          //       code: url,
          //       orderNum: index
          //     })
          //   })
          // }
          that.confirmLoading = true
          let formData = Object.assign({}, this.model, values, this.areaLinkage)

          formData.extendVos = this.formItems

          postAction(this.url.add, formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    },
    handleCancel() {
      this.close()
    }
  },
  created() {
    this.initAreaData()
    this.loadTree()
  },
  computed: {
    modalProps() {
      return Object.assign({}, {
        name: this.name
      })
    },
    configw() {
      return {
        title: '新增发票信息',
        width: '40%',
        config: {
          list: [
            {
              label: '客户名称',
              type: 'input',
              disabled: true,
              placeholder: '请输入路由ID',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '上账科目编码',
              type: 'input',
              placeholder: '请输入上账科目编码',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '发票编码',
              type: 'input',
              placeholder: '请输入发票编码',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '税码',
              type: 'input',
              placeholder: '请输入税码',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '发票金额',
              type: 'input',
              placeholder: '请输入发票金额(不含税)',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '发票金额',
              type: 'input',
              placeholder: '请输入发票金额(含税)',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '税金',
              type: 'input',
              placeholder: '请输入税金',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: 'ERP成本中心',
              type: 'input',
              placeholder: '请输入ERP成本中心',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            },
            {
              label: '摘要',
              type: 'input',
              placeholder: '请输入摘要',
              name: 'routeId',
              check: { rules: [{ required: true, message: '请输入' }] }
            }
          ]
        }
      }
    }
  }
}
</script>

<style lang='less' scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

.basicNew {
  padding: 8px 6px 8px 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
  font-size: 16px;
  font-weight: 700;
}

.basicNew1 {
  padding: 8px 6px 8px 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
  font-size: 16px;
  font-weight: 700;
}

.addIcon {
  background-color: #4d80be;
  color: #FFFFFF;
}
.tableImages {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}
.dianzhao-pic{
  display:flex;
  flex-direction: column;
  align-items:center;

}
/deep/ .ant-upload.ant-upload-select-picture-card{
  margin:0 auto !important;
  width:100%;
}
</style>